package com.xjscrm.server.service.customer.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.msg.MicaContactMsg;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendAddMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerBatchMarkLabelMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerCustomerSetRemarkMsg;
import com.uzai.mobile.collect.api.enums.MicaMsgSource;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.*;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.custmoerplan.CustomerPlanRule;
import com.xjscrm.common.vo.custmoerplan.TriggerCondition;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupPullMsgData;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.biz.mq.producer.SendMsgProducer;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.Functions;
import com.xjscrm.server.common.util.SleepTimeTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.customer.WwCustomerService;
import com.xjscrm.server.service.customer.WwCustomerSyncService;
import com.xjscrm.server.service.grouppull.GroupPullConfigService;
import com.xjscrm.server.service.grouppull.GroupPullDataService;
import com.xjscrm.server.service.msg.MsgSendService;
import com.xjscrm.server.service.soptask.SopJobHanderService;
import com.xjscrm.server.service.soptask.SopJobNewCustomerService;
import com.xjscrm.server.service.soptask.SopJobTagService;
import com.xjscrm.server.vo.customer.CustomerAddVerifyResult;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信客户添加实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwCustomerServiceImpl implements WwCustomerService {
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private OperatePlanDeviceMapper operatePlanDeviceMapper;
    @Autowired
    private OperatePlanMapper operatePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private WwFriendReqMapper wwFriendReqMapper;
    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;
    @Autowired
    private MsgSendService msgSendService;
    @Autowired
    private WwTagsMapper wwTagsMapper;
    @Autowired
    private CustomerBehaviorMapper customerBehaviorMapper;
    @Autowired
    private GroupPullDataService groupPullDataService;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private SopJobHanderService sopJobHanderService;
    @Autowired
    private SopJobNewCustomerService sopJobNewCustomerService;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private SopJobTagService sopJobTagService;
    @Autowired
    private WwCustomerSyncService wwCustomerSyncService;
    @Resource
    private GroupPullConfigService groupPullConfigService;

    /**
     * 企微好友通过
     *
     * @param micaTransDto 企微好友通过
     * @return 实例对象
     */
    @Async("taskExecutorForNewCustomer")
    @TraceGenerate //注入消息id标签
    public void customerAdd(MicaTransDto micaTransDto) {
        try {

            MicaFriendAddMsg micaFriendAddMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaFriendAddMsg.class);
            if(micaFriendAddMsg == null){
                return;
            }

            //限流判断(同一个会员，同一个机器人5秒内只能请求一次)
            String rateLimitKey = "customerAdd-taskId=" + micaTransDto.getDeviceId() + "_" + micaFriendAddMsg.getWxid();
            boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 1, 5);
            if (!inRateLimit) {
                return;
            }

            log.info("--进入通过好友请求处理方法--");


            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //默认黑名单不通过
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(micaTransDto.getMerId(), micaFriendAddMsg.getWxid());
            if(wwCustomerBlacklist != null){ //在黑名单中
                log.info("黑名单会员，wxid={}", micaFriendAddMsg.getWxid());
                return ;
            }

            //查询机器人
            log.info("--监控系统日志--查询机器人--");
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            log.info("--监控系统日志--查询机器人信息wwDevice={}", JSONObject.toJSONString(wwDevice));

            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                log.info("未找到该机器人，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
                return;
            }

            //处理好友请求
            log.info("--监控系统日志--查询好友--");
            int now = DateUtil.getTime();
            WwFriendReq wwFriendReq = wwFriendReqMapper.queryByDeviceIdAndWxid(micaTransDto.getDeviceId(), micaFriendAddMsg.getWxid(), micaTransDto.getMerId());
            if (wwFriendReq != null) {
                wwFriendReq.setStatus(FriendReqStatusEnum.PASSED.getId());
                wwFriendReq.setUpdateTime(now);
                wwFriendReq.setOptTime(now);
                wwFriendReqMapper.update(wwFriendReq);
            }

            //新客户添加
            log.info("--监控系统日志--查询客户--");
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getId(), micaFriendAddMsg.getWxid());
            if (wwCustomer != null) {
                log.info("该客户已经存在，wwCustomer={}", JSONObject.toJSONString(wwCustomer));
                return;
            }

            //查询好友申请,查询到为客户主动申请，查询不到默认为机器人主动添加
            wwCustomer = new WwCustomer();
            wwCustomer.setId(IdWorker.getId());
            wwCustomer.setMerId(device.getMerId());
            wwCustomer.setDeviceUniqueId(device.getId());
            wwCustomer.setStatus(1); //正常
            wwCustomer.setWxid(micaFriendAddMsg.getWxid());
            wwCustomer.setRemark(micaFriendAddMsg.getRemark());
            wwCustomer.setDescription("系统添加");
            wwCustomer.setCreateTime(now);
            wwCustomer.setUpdateTime(now);

            if (wwFriendReq != null) { //有好友请求，客户主动添加添加
                micaFriendAddMsg.setHeadImg(wwFriendReq.getHeadImg());
                micaFriendAddMsg.setNickName(wwFriendReq.getNickName());
                micaFriendAddMsg.setGender(wwFriendReq.getGender());
                micaFriendAddMsg.setScene(wwFriendReq.getScene());
                wwCustomer.setAddType(CustomerAddTypeEnum.CUSTOMER_ACTIVE.getId()); //添加方式（0-客户主动添加；2-机器人主动添加）
            } else { //没好友请求，机器人主动添加添加
                wwCustomer.setAddType(CustomerAddTypeEnum.DEVICE_ACTIVE.getId()); //添加方式（0-客户主动添加；2-机器人主动添加）
            }

            wwCustomer.setHeadImgUrl(micaFriendAddMsg.getHeadImg());
            wwCustomer.setName(micaFriendAddMsg.getNickName());
            wwCustomer.setGender(Tools.getInteger(micaFriendAddMsg.getGender()));
            wwCustomer.setNickname(null);
            wwCustomer.setScene(Tools.getInteger(micaFriendAddMsg.getScene()));
            wwCustomerMapper.insert(wwCustomer);
            log.info("--插入会员成功--wwCustomer={}", JSONObject.toJSONString(wwCustomer));

            log.info("--监控系统日志--添加会员--");
            //wwCustomerSyncService.addTagForExternalUserid(wwCustomer.getMerId(), wwDevice, wwCustomer);
            //log.info("--监控系统日志--调用新客户获取外部账号接口--");

            //触发SOP任务-添加新客户
            sopJobNewCustomerService.addSopJobByNewCustomer(wwCustomer, device);

            log.info("--监控系统日志--异步执行新客户SOP任务--");

            //添加行为轨迹
            CustomerBehavior customerBehavior = new CustomerBehavior();
            customerBehavior.setId(IdWorker.getId());
            customerBehavior.setMerId(wwCustomer.getMerId());
            customerBehavior.setDeviceUniqueId(wwCustomer.getDeviceUniqueId());
            customerBehavior.setCustomerId(wwCustomer.getId());
            customerBehavior.setType(CustomerBehaviorTypeEnum.CUSTOMER_REGISTER_VALUE);
            String msg = "新好友注册，来源[%s]";
            WwFriendReqScene wwFriendReqScene = WwFriendReqScene.getById(wwCustomer.getScene());
            if (wwFriendReqScene != null) {
                msg = String.format(msg, wwFriendReqScene.getDesc());
            } else {
                msg = String.format(msg, WwFriendReqScene.UN_KNOW.getDesc());
            }
            customerBehavior.setMsg(msg);
            customerBehavior.setCreateTime(now);
            customerBehavior.setUpdateTime(now);
            customerBehaviorMapper.insert(customerBehavior);

            log.info("--监控系统日志--插入行为轨迹--");

            //保存添加好友数+1
            String autoAuditCount_redis_key = String.format(RedisCacheKeyEnum.NEW_CUSTOMER_PLAN_AUTO_AUDIT_COUNT.getKey(), device.getDeviceId());
            //计算当前时间与次日凌晨的差值
            long leftTime = Tools.getSecondsTobeforedawn();
            //更新缓存
            redisTemplate.opsForValue().increment(autoAuditCount_redis_key);
            redisTemplate.expire(autoAuditCount_redis_key, leftTime, TimeUnit.SECONDS);

            //启用的机器人对应的方案
            OperatePlanDevice operatePlanDevice_use = null;
            //查询客户运营方案对应的条件规则
            TriggerCondition triggerCondition_use = null;
            //条件验证方案
            OperatePlanDevice operatePlanDevice_para = operatePlanDeviceMapper.queryCustomerAddByDeviceUniqueId(2, device.getId(), device.getMerId());
            if (operatePlanDevice_para != null) {
                OperatePlan operatePlan__para = operatePlanMapper.queryById(operatePlanDevice_para.getPlanId());
                if (operatePlan__para != null) {
                    //条件验证结果
                    CustomerAddVerifyResult customerAddVerifyResult = verifyPara(operatePlan__para, micaFriendAddMsg, wwCustomer.getAddType());
                    if (customerAddVerifyResult != null && customerAddVerifyResult.isPass()) {
                        triggerCondition_use = customerAddVerifyResult.getTriggerCondition();
                        operatePlanDevice_use = operatePlanDevice_para; //采用此方案。将此方案临时标志
                    }
                }
            }

            //如果运营方案还未空，则表示未通过条件限制，则选择默认方案对应的条件
            if (triggerCondition_use == null) {
                //默认方案
                OperatePlanDevice operatePlanDevice_default = operatePlanDeviceMapper.queryCustomerAddByDeviceUniqueId(1, device.getId(), device.getMerId());
                if (operatePlanDevice_default != null) {
                    OperatePlan operatePlan__default = operatePlanMapper.queryById(operatePlanDevice_default.getPlanId());
                    if (operatePlan__default != null) {
                        if (StringUtils.isNotBlank(operatePlan__default.getPlanRule())) {
                            //条件限制
                            CustomerPlanRule customerPlanRule = JSONObject.parseObject(operatePlan__default.getPlanRule(), CustomerPlanRule.class);
                            if (customerPlanRule != null) {
                                //条件限制
                                List<TriggerCondition> triggerConditions = customerPlanRule.getTriggerConditions();
                                if (triggerConditions != null && triggerConditions.size() > 0) {
                                    triggerCondition_use = triggerConditions.get(0);
                                    operatePlanDevice_use = operatePlanDevice_default;
                                }
                            }
                        }
                    }
                }
            }

            log.info("--监控系统日志--进行新客运营判断--");

            if (triggerCondition_use == null) {
                log.info("未找到该机器人符合该新客户运营方案规则，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
                List<MsgData> msgDatas = new ArrayList<>();
                MsgData msgData = new MsgData();
                msgData.setMsgType(1);
                msgData.setContent("您好，很高兴认识你!");
                msgDatas.add(msgData);
                //msgSendService.msgSend(device, wwCustomer.getWxid(), msgDatas);
                return;
            }

            log.info("--监控系统日志--进行新客运营判断--operatePlanDevice_use={}", JSONObject.toJSONString(operatePlanDevice_use));

            //处理发送消息（判断该配置方案对应的机器人是否休眠）

            if (operatePlanDevice_use != null) {
                OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(operatePlanDevice_use.getRule(), OperatorPlanDeviceRule.class);
                boolean sleepTimeFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                //此时属于休眠时间
                log.info("--监控系统日志--新客户运营机器人是否休眠--sleepTimeFlag={}", sleepTimeFlag);
                if(!sleepTimeFlag){
                    //发送消息
                    log.info("--监控系统日志--新客户运营触发条件--triggerCondition_use={}", JSONObject.toJSONString(triggerCondition_use));
                    if(triggerCondition_use != null){
                        List<GroupPullData> groupPullDataList = triggerCondition_use.getMsgDatas();
                        List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(micaTransDto.getMerId(), groupPullDataList, wwCustomer, device);
                        //封装新客户运营消息数据
                        log.info("--监控系统日志--发送新客运营消息数据--groupPullMsgDataList={}", JSONObject.toJSONString(groupPullMsgDataList));
                        if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                            msgSendService.groupPullMsgSendForCustomerAdd(device.getMerId(), device, wwCustomer, groupPullMsgDataList, 4, operatePlanDevice_use.getPlanId(), false, null, MicaMsgSource.NEW_CUSTOMER_OPERATOR.getCode(), false);
                            log.info("--监控系统日志--送新客运营消息完成发--");
                        }
                    }
                }
            }

            //自动打标签
            //是否成功打标签判断
            boolean addTagFlag = false;
            List<Long> tagIds = triggerCondition_use.getTagIds();
            if (tagIds != null && tagIds.size() > 0) {
                for (Long tagId : tagIds) {
                    WwTags wwTags = wwTagsMapper.queryById(tagId);
                    if (wwTags != null) {
                        //验证此标签是否跟机器人属于同一企业，如果不是，则不打标签
                        if(Tools.getInteger(wwTags.getType()).intValue() == 1){ //企业标签才判断
                            if(!Tools.getStr(device.getCorpId()).equals(Tools.getStr(wwTags.getCorpId()))){
                                continue;
                            }
                        }

                        WwCustomerTags wwCustomerTags = new WwCustomerTags();
                        wwCustomerTags.setId(IdWorker.getId());
                        wwCustomerTags.setMerId(device.getMerId());
                        wwCustomerTags.setTagId(tagId);
                        wwCustomerTags.setTagIdStr(wwTags.getTagId());
                        wwCustomerTags.setCustomerId(wwCustomer.getId());
                        wwCustomerTags.setCreateTime(DateUtil.getTime());
                        wwCustomerTags.setUpdateTime(DateUtil.getTime());
                        wwCustomerTagsMapper.insert(wwCustomerTags);
                        groupPullConfigService.groupPushByEnterpriseTag(device, wwCustomer, wwCustomerTags.getTagId());

                        addTagFlag = true;

                        log.info("--监控系统日志--添加客户标签--");

                        //添加行为轨迹
                        CustomerBehavior customerBehavior_tag = new CustomerBehavior();
                        customerBehavior_tag.setId(IdWorker.getId());
                        customerBehavior_tag.setMerId(wwCustomer.getMerId());
                        customerBehavior_tag.setDeviceUniqueId(wwCustomer.getDeviceUniqueId());
                        customerBehavior_tag.setCustomerId(wwCustomer.getId());
                        customerBehavior_tag.setType(CustomerBehaviorTypeEnum.CUSTOMER_REGISTER_VALUE);
                        String msg_tag = "注册时自动打标签，新标签[%s]";
                        msg_tag = String.format(msg_tag, wwTags.getTagName());
                        customerBehavior_tag.setMsg(msg_tag);
                        customerBehavior_tag.setCreateTime(DateUtil.getTime());
                        customerBehavior_tag.setUpdateTime(DateUtil.getTime());
                        customerBehaviorMapper.insert(customerBehavior_tag);

                        log.info("--监控系统日志--添加行为--");

                        //发送自动打标签指令
                        try {
                            MicaTriggerBatchMarkLabelMsg micaTriggerBatchMarkLabelMsg = new MicaTriggerBatchMarkLabelMsg();
                            micaTriggerBatchMarkLabelMsg.setLabelId(wwTags.getTagId());
                            micaTriggerBatchMarkLabelMsg.setIsCorp(Tools.getInteger(wwTags.getType()).intValue() == 1 ? true : false); //是否是企业标签
                            micaTriggerBatchMarkLabelMsg.setAddWxIds(Lists.newArrayList(wwCustomer.getWxid()));
                            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerBatchMarkLabelMsg, MicaTriggerType.TRIGGER_BATCH_MARK_LABEL, Functions.fillTriggerMsg(device));
                            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息

                            log.info("--监控系统日志--发送自动打标签指令--");
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }

            if(addTagFlag){
                //触发SOP任务-自动打标签
                sopJobTagService.addSopJobByPushCustomerTag(micaTransDto.getMerId(), wwDevice, wwCustomer);
            }

            //自动备注
            Integer remarkSwitch = triggerCondition_use.getRemarkSwitch();
            String remark = triggerCondition_use.getRemark();
            if (Tools.getInteger(remarkSwitch).intValue() == 1 && StringUtils.isNotBlank(remark)) {
                remark = remark.replace("[微信昵称]", Tools.getStr(wwCustomer.getName()));
                //客户性别
                String gender = "";
                GenderEnum genderEnum = GenderEnum.getById(Tools.getInteger(wwCustomer.getGender()));
                if (genderEnum != null) {
                    gender = genderEnum.getDesc();
                }
                remark = remark.replace("[性别]", Tools.getStr(gender));
                //添加日期
                remark = remark.replace("[添加日期]", Tools.getDateFormat(new Date(now * 1000L), "yyMMdd"));
                //手机号
                remark = remark.replace("[手机号]", Tools.getStr(wwCustomer.getMobile()));
                wwCustomer.setRemark(remark);
                wwCustomer.setUpdateTime(DateUtil.getTime());
                wwCustomerMapper.update(wwCustomer);

                log.info("--监控系统日志--修改备注--");

                //添加行为轨迹
                CustomerBehavior customerBehavior_remark = new CustomerBehavior();
                customerBehavior_remark.setId(IdWorker.getId());
                customerBehavior_remark.setMerId(wwCustomer.getMerId());
                customerBehavior_remark.setDeviceUniqueId(wwCustomer.getDeviceUniqueId());
                customerBehavior_remark.setCustomerId(wwCustomer.getId());
                customerBehavior_remark.setType(CustomerBehaviorTypeEnum.CUSTOMER_UPDATE_REMARK_VALUE);
                String msg_remark = "注册时自动修改备注，新备注[%s]";
                msg_remark = String.format(msg_remark, wwCustomer.getRemark());
                customerBehavior_remark.setMsg(msg_remark);
                customerBehavior_remark.setCreateTime(DateUtil.getTime());
                customerBehavior_remark.setUpdateTime(DateUtil.getTime());
                customerBehaviorMapper.insert(customerBehavior_remark);


                log.info("--监控系统日志--添加备注轨迹--");

                //发送自动备注指令
                try {
                    MicaTriggerCustomerSetRemarkMsg micaTriggerBatchMarkLabelMsg = new MicaTriggerCustomerSetRemarkMsg();
                    micaTriggerBatchMarkLabelMsg.setWxid(wwCustomer.getWxid());
                    micaTriggerBatchMarkLabelMsg.setRemark(remark); //新备注
                    MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerBatchMarkLabelMsg, MicaTriggerType.TRIGGER_SET_REMARK, Functions.fillTriggerMsg(device));
                    sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        log.info("--监控系统日志--结束方法--");
    }

    /**
     * 企业微信新客户方案验证接口
     *
     * @param operatePlan 新好友申请实体类
     * @return 实例对象
     */
    private CustomerAddVerifyResult verifyPara(OperatePlan operatePlan, MicaFriendAddMsg micaFriendAddMsg, int addType) {
        //返回对象
        CustomerAddVerifyResult customerAddVerifyResult = new CustomerAddVerifyResult();
        customerAddVerifyResult.setPass(false); //默认不通过
        customerAddVerifyResult.setTriggerCondition(null);
        if (operatePlan == null) {
            return customerAddVerifyResult;
        }

        //条件限制
        CustomerPlanRule customerPlanRule = JSONObject.parseObject(operatePlan.getPlanRule(), CustomerPlanRule.class);
        if (customerPlanRule == null) {
            log.info("条件为空，planId={}", operatePlan.getId());
            return customerAddVerifyResult;
        }

        //条件限制
        List<TriggerCondition> triggerConditions = customerPlanRule.getTriggerConditions();
        if (triggerConditions != null && triggerConditions.size() > 0) {
            for (TriggerCondition triggerCondition : triggerConditions) {
                //性别验证
                boolean flagGender = false;
                //性别
                List<Integer> genders = triggerCondition.getGenders();
                if (genders != null && genders.size() > 0) {
                    //性别验证
                    flagGender = genders.contains(micaFriendAddMsg.getGender());
                } else {
                    flagGender = true;
                }
                //来源验证
                boolean flagScene = false;
                //来源
                List<Integer> scenes = triggerCondition.getScenes();
                if (scenes != null && scenes.size() > 0) {
                    //来源验证
                    flagScene = scenes.contains(micaFriendAddMsg.getScene());
                } else {
                    flagScene = true;
                }
                //添加方式
                boolean flagAddType = false;
                List<Integer> addTypes = triggerCondition.getAddTypes();
                if (addTypes != null && addTypes.size() > 0) {
                    //来源验证
                    flagAddType = addTypes.contains(addType);
                } else {
                    flagAddType = true;
                }

                //三个都同时满足，才满足条件验证
                if (flagGender && flagScene && flagAddType) {
                    customerAddVerifyResult.setPass(true);   //满足限制条件
                    //获取此条件对应的规则
                    customerAddVerifyResult.setTriggerCondition(triggerCondition);

                    return customerAddVerifyResult;
                }
            }
        }

        return customerAddVerifyResult;
    }

    /**
     * 同步企业微信通讯录
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void contactPush(MicaTransDto micaTransDto) {
        log.info("--监控系统同步通讯录日志--开始--");

        if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
            log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
            return;
        }

        //查询该机器人
        log.info("--监控系统日志--查询机器人--");
        WwDevice wwDevice  = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
        if(wwDevice == null){
            log.info("未找到该机器人，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
            return;
        }

        int now = DateUtil.getTime();

        //更新最后更新同步群时间
        wwDevice.setLastSyncSuctomerGroupTime(now);
        wwDevice.setUpdateTime(now);
        wwDeviceMapper.update(wwDevice);

        //查询该机器人的配置方案
        Device device = DeviceTools.transDevice(wwDevice);
        if (device == null) {
            log.info("未找到该机器人，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
            return;
        }

        MicaContactMsg micaContactMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaContactMsg.class);
        if (micaContactMsg != null) {
            List<MicaContactMsg.ContactItemMsg> users = micaContactMsg.getUsers();
            if (users != null && users.size() > 0) {
                for (MicaContactMsg.ContactItemMsg user : users) {

                    //限流判断(同一个机器人30秒之内只能操作一次)
                    String rateLimitKey = "contactPush-deviceId-wxid=" + micaTransDto.getDeviceId() + "_" + user.getWxId();
                    Object rateLimitKey_object = redisTemplate.opsForValue().get(rateLimitKey);
                    if(rateLimitKey_object == null){
                        redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 100, TimeUnit.SECONDS);
                    }else{
                        continue;
                    }

                    try {
                        //判断存不存在，不存在则添加
                        WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), user.getWxId());
                        if (wwCustomer == null) {
                            wwCustomer = new WwCustomer();
                            wwCustomer.setId(IdWorker.getId());
                            wwCustomer.setMerId(micaTransDto.getMerId());
                            wwCustomer.setDeviceUniqueId(device.getDeviceUniqueId());
                            wwCustomer.setName(user.getUserName());
                            wwCustomer.setRemark(user.getRemark());
                            wwCustomer.setGender(Tools.getInteger(user.getGender()));
                            wwCustomer.setNickname("");
                            wwCustomer.setStatus(1); //正常
                            wwCustomer.setWxid(user.getWxId());
                            wwCustomer.setHeadImgUrl(user.getHeadImg());
                            wwCustomer.setScene(WwFriendReqScene.UN_KNOW.getValue());        //未知来源
                            wwCustomer.setDescription("自动更新通讯录添加");
                            wwCustomer.setAddType(CustomerAddTypeEnum.UN_KNOW.getId()); //未知
                            wwCustomer.setMobile(user.getMobile());
                            //wwCustomer.setCorpId(user.getCorpId());
                            wwCustomer.setPushTime(now);
                            wwCustomer.setCreateTime(now);
                            wwCustomer.setUpdateTime(now);
                            //插入
                            wwCustomerMapper.insert(wwCustomer);

                            //wwCustomerSyncService.addTagForExternalUserid(wwCustomer.getMerId(), wwDevice, wwCustomer);
                            //log.info("--监控系统日志--调用新客户获取外部账号接口--");

                            log.info("--监控系统日志--插入会员--");

                        } else {
                            wwCustomer.setName(user.getUserName());
                            wwCustomer.setRemark(user.getRemark());
                            wwCustomer.setGender(Tools.getInteger(user.getGender()));
                            wwCustomer.setHeadImgUrl(user.getHeadImg());
                            wwCustomer.setMobile(user.getMobile());
                            //wwCustomer.setCorpId(user.getCorpId());
                            wwCustomer.setPushTime(now);
                            wwCustomer.setUpdateTime(now);
                            wwCustomerMapper.update(wwCustomer);

                            log.info("--监控系统日志--修改会员--");

                            //删除该会员标签，然后在更新最新标签
                            wwCustomerTagsMapper.deleteByCustomerId(wwCustomer.getId());

                            log.info("--监控系统日志--删除会员标签--");

                        }

                        //同步标签
                        List<String> labelIds = user.getLabelIds();
                        if (labelIds != null && labelIds.size() > 0) {
                            for (String labelId : labelIds) {
                                //查询此标签存不存在，如果不存在，则不入库
                                WwTags wwTags = wwTagsMapper.queryByTagIdStr(micaTransDto.getMerId(), labelId);
                                if (wwTags != null) {
                                    //找到该标签，才更新该会员标签
                                    WwCustomerTags wwCustomerTags = wwCustomerTagsMapper.queryByCustomerIdAndTagIdStr(wwCustomer.getId(), labelId);
                                    if (wwCustomerTags == null) {
                                        wwCustomerTags = new WwCustomerTags();
                                        wwCustomerTags.setId(IdWorker.getId());
                                        wwCustomerTags.setMerId(wwCustomer.getMerId());
                                        wwCustomerTags.setTagId(wwTags.getId());
                                        wwCustomerTags.setTagIdStr(labelId);
                                        wwCustomerTags.setCustomerId(wwCustomer.getId());
                                        wwCustomerTags.setCreateTime(now);
                                        wwCustomerTags.setUpdateTime(now);
                                        wwCustomerTagsMapper.insert(wwCustomerTags);
                                        groupPullConfigService.groupPushByEnterpriseTag(device, wwCustomer, wwCustomerTags.getTagId());
                                        log.info("--监控系统日志--同步会员标签--");
                                    }
                                }
                            }
                        }
                    }catch (Exception e){
                        log.error(e.getMessage(), e);
                    }finally {
                        redisTemplate.delete(rateLimitKey);
                    }
                }
            }
        }

    }

}
